<template>
    <div class="user-chart">
         <van-nav-bar
            class="app-nav-bar"
            title="小智同学"
            @click-left="$router.back()"
            >
            <div slot="left">
            <van-icon color="#fff" size="25" name="arrow-left" />
            </div>
        </van-nav-bar>

        <!-- 消息列表 -->
        <div class="message-list" ref="message-list">
            <!-- <van-cell center  :title="message.msg" v-for="(message,index) in messageList" :key="index"/> -->
          <div  v-for="(message,index) in messageList" :key="index">
            <van-cell  class="send-message"  :border="false" v-if="message.sendMessage">
                <p slot="default" class="message" >{{ message.msg }}</p>
                <div slot="right-icon">
                    <van-image
                        width="40"
                        height="40"
                        :src="userInfo.photo"
                        round
                        fit="cover"
                    />
                </div>
            </van-cell>

             <van-cell  class="recive-message"  :border="false" v-else>
                <div slot="icon">
                    <van-image
                        width="40"
                        height="40"
                        :src="defaultPhoto"
                        round
                        fit="cover"
                    />
                </div>
                <p slot="title" class="message" >{{ message.msg }}</p>
             </van-cell>
          </div>
        </div>
        <!-- 底部输入框 -->
        <van-cell-group class="send-content" border>
          <van-field
            v-model="message"
            center
            clearable
            placeholder="请输入聊天内容"
            >
                <template #button>
                    <van-button hairline size="small" type="primary" @keyup.enter="sendMessage" @click="sendMessage">发送消息</van-button>
                </template>
            </van-field>
        </van-cell-group>
    </div>
</template>

<script>
import io from 'socket.io-client'
import { mapState } from 'vuex'
import { getItem,setItem }  from '@/utils/storage'
import { getUserProfile } from '@/api/user'
import { Notify } from 'vant'
export default {
    name: 'ToutiaoMIndex',
    data() {
        return {
            message:'',
            socket: null,
            messageList: getItem('chart-list') || [],
            defaultPhoto:'http://toutiao.itheima.net/images/user_head.jpg',
            userInfo:{}
            // sendMessages:[],  //发送的消息
            // reciveMessages:[]  // 收到的消息
        }
    },
    created () {
        const socket = io('https://toutiao.itheima.net',{
             query: {
                token: this.tokenInfo.token || getItem('user-token').token ,
            },
            transports: ['websocket']
        })
        this.socket = socket
        this.socket.on('connect', () =>{
            console.log('链接成功')
        })
        // window.socket = this.socket
        this.socket.on('message', (reviceMessage) => {
            this.messageList.push(reviceMessage)
            console.log(reviceMessage)
        })

        // 获取用户信息
        this.loadUserProfile()
    },

    mounted() {
        this.scrollBottom()
    },
    computed: {
        ...mapState('user',['tokenInfo'])
    },
    watch: {
        messageList (){
            // 数据更新后视图不会立即更新，需要等到视图更新后执行延迟回调
            this.$nextTick( ()=> {
                this.scrollBottom()
            })
            setItem('chart-list',this.messageList)
        }
    },
    methods: {
        sendMessage () {
            if (this.message === "" || this.message.trim() === "") {
                Notify({
                    message: '消息内容不能为空',
                    duration: 1000,
                })
            }else{
                let sendData = {
                    "msg": this.message,
                    "timestamp": Date.now(),
                    "sendMessage":1
                }
                this.messageList.push(sendData)
                this.socket.emit('message', sendData)
                this.message = ''
            }
        },
        scrollBottom () {
            let messageWrap = this.$refs['message-list']
            messageWrap.scrollTop = messageWrap.scrollHeight
        },
        async loadUserProfile () {
            const { data:{ data } } = await getUserProfile()
            console.log(data)
            this.userInfo = data
        }
    },
};
</script>

<style lang="less" scoped>
.user-chart{
    height: 100%;
    .send-content{
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
    }
    .message-list{
        position: fixed;
        top: 46px;
        left: 0;
        right: 0;
        bottom: 53px;
        overflow: auto;
        .send-message{
            min-height: 58px;
            display: flex;
            justify-content: flex-end;
            // align-items: center;
            align-items: flex-start;
           .van-cell__value {
                max-width: 200px;
                font-size: .37333rem;
                color: #333;
                border-radius: 10px;
                display: inline-block;
                width: auto;
                // display:inline-block;
                display: flex;
                justify-content: flex-end;
                p{
                    text-align: left;
                    max-width: 200px;
                    border-radius: 10px;
                    padding: 10px;
                    background-color: #f7f8fa;
                    display: inline-block;
                    word-break: break-all;
                    margin-right: 5px;
                }

           }

        }
        .recive-message{
            min-height: 58px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
           .van-cell__title {
                max-width: 200px;
                font-size: .37333rem;
                color: #333;
                border-radius: 10px;
                display: inline-block;
                width: auto;
                display: flex;
                justify-content: flex-start;
                p{
                    text-align: left;
                    max-width: 200px;
                    border-radius: 10px;
                    padding: 10px;
                    background-color: #f7f8fa;
                    display: inline-block;
                    word-break: break-all;
                    margin-left: 5px;
                }

           }

        }
    }
}
</style>
